
var pkg = "firewall";
var homeuserprefix = "homeuser_";
var userdata = "gargoyle";
var userMac;

function verifyUser()
{
	var arpHash = parseArp(arpLines);
	var homeuserMac = arpHash[ connectedIp ];
	userMac = homeuserMac.replace(/^[\t ]*/, "");
	userMac = homeuserMac.replace(/[\t ]*$/, "");
	currentDay = currentDay.toLowerCase();
	for (homeuserIndex=1;uciOriginal.get(userdata,homeuserprefix+homeuserIndex) != "" && homeuserIndex<10 ;homeuserIndex++)
	{
	if(userMac == uciOriginal.get(userdata,homeuserprefix+homeuserIndex,"macaddr"))
	{var Homeuserloggedin = true;}
	}
	if(Ishomeuser)
		{
			homepassInvalid=false;	
			doHomeuseractive();		
		}
	else
		{
        		homepassInvalid=true;
			setHomeUserStatusAndQuotas();
		}
	}

}

function parseArp(arpLines)
{
	var arpHash = [];
	
	arpLines.shift(); //skip header
	var lineIndex = 0;
	for(lineIndex=0; lineIndex < arpLines.length; lineIndex++)
	{
		var nextLine = arpLines[lineIndex];
		var splitLine = nextLine.split(/[\t ]+/);
		var mac = splitLine[3].toUpperCase();
		var ip = splitLine[0];
		arpHash[ mac ] = ip;
		arpHash[ ip  ] = mac;
	}

	return arpHash;
}

function doHomeuseractive()
{
	
	var arpHash = parseArp(arpLines);
	var tableContainer = document.getElementById("exception_applies_to_table_container");
	var homeuserMac = arpHash[ connectedIp ];
	Userloggedin = true;
	MacAddrs = homeuserMac.replace(/^[\t ]*/, "");
	MacAddrs = homeuserMac.replace(/[\t ]*$/, "");
	//var addrs = MacAddrs.split(/[\t ]*,[\t ]*/);
	/*var table = tableContainer.childNodes.length > 0 ? tableContainer.firstChild : createTable([""], [], "exception_applies_to_table" , true, false);
	while(addrs.length > 0)
		{
			addTableRow(table, [ addrs.shift() ], true, false);
		}
	if(tableContainer.childNodes.length == 0)
		{
			tableContainer.appendChild(table);
		}
	*/
	currentDay = currentDay.toLowerCase();
	var sectionId = "Homecafe_allow";
	var ruleType = "whitelist_rule";
	var rulePrefix = "exception_1";
	var runCommands = [];	
	var userID = document.getElementById("userID").value;

	

	var deleteSectionCommands = [];
	var createSectionCommands = [];		
		//delete all sections of type in uciOriginal & remove them from uciOriginal
	deleteSectionCommands.push("uci del " + pkg + "." + rulePrefix);
	createSectionCommands.push("uci set " + pkg + "." + rulePrefix + "='" + ruleType + "'");
	createSectionCommands.push("uci set " + pkg + "." + rulePrefix + "." + "local_addr" + "=" + MacAddrs);
	createSectionCommands.push("uci set " + pkg + "." + rulePrefix + "." + "description" + "=" + userID);
	createSectionCommands.push("uci set " + pkg + "." + rulePrefix + "." + "active_weekdays" + "=" + currentDay);
	createSectionCommands.push("uci set " + pkg + "." + rulePrefix + "." + "is_ingress" + "='0'");
	createSectionCommands.push("uci set " + pkg + "." + rulePrefix + "." + "enabled" + "='1'");	
	
	deleteSectionCommands.push("uci commit");
	createSectionCommands.push("uci commit");
	setControlsEnabled(false, true,"Home User Logging In");
	

	var commands = deleteSectionCommands.join("\n") + "\n" + createSectionCommands.join("\n") + "\n" /*+ uci.getScriptCommands(uciOriginal) + "\n" + runCommands.join("\n") + "\n"*/ + "sh /usr/lib/gargoyle/restart_firewall.sh";

	var param = getParameterDefinition("commands", commands);

	var stateChangeFunction = function(req)
	{
		if(req.readyState == 4)
		{	
			setControlsEnabled(true);
			Homeusercountdown(userID);			
			//alert("You successfully logged in!");
		}
	}
	runAjax("POST", "utility/run_home_commands.sh", param, stateChangeFunction);
}



function Homeusercountdown(userID)
{
	document.getElementById("counter_down_timer").style.display = "block";
	setChildText("current_homeuser",userID);
	TimerID = "User_time_left";
	var Limit_time_second = 0;
	var Hours = 0;
	var Minutes = 5;
	Limit_time_second += Hours * (3600);
	Limit_time_second += Minutes * (60);
	CreateTimer(TimerID,Limit_time_second);
}

var TotalSeconds;
var Timer;

function CreateTimer(TimerID, Time) {
    Timer = TimerID;
    TotalSeconds = Time;
    
    UpdateTimer();
    window.setTimeout("Tick()", 1000);
}

function Tick() {
    if (TotalSeconds <= 0) {
        alert("Time's up!")
        return;
    }

    TotalSeconds -= 1;
    UpdateTimer()
    window.setTimeout("Tick()", 1000);
}

function UpdateTimer() {
    var Seconds = TotalSeconds;
    
    var Days = Math.floor(Seconds / 86400);
    Seconds -= Days * 86400;

    var Hours = Math.floor(Seconds / 3600);
    Seconds -= Hours * (3600);

    var Minutes = Math.floor(Seconds / 60);
    Seconds -= Minutes * (60);


    var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)


    setChildText(Timer,TimeStr);
}


function LeadingZero(Time) {

    return (Time < 10) ? "0" + Time : + Time;

}

function doHomeUserLogin()
{
	var userID = document.getElementById("userID").value;
	if(userID.length == 0)
		{
			alert("ERROR: You must enter a Home user ID");
		}
	else
	{
	for (homeuserIndex=1;uciOriginal.get("gargoyle","homecafe",homeuserprefix+homeuserIndex) != "" && homeuserIndex<10 ;homeuserIndex++)
	{
	if(userID == uciOriginal.get("gargoyle","homecafe",homeuserprefix+homeuserIndex))
	{var Ishomeuser = true;}
	}
	if(Ishomeuser)
		{
			homepassInvalid=false;	
			doHomeuseractive();		
		}
	else
		{
        		homepassInvalid=true;
			setHomeUserStatusAndQuotas();
		}
	}
}

function setHomeUserStatusAndQuotas()
{ 
        if(homepassInvalid)
	{
		setChildText("homeuser_login_status", "Invalid User ID", "red");
	}
}




